package com.glasses.business.fragment;

import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.alibaba.sdk.android.oss.model.OSSException;
import com.facebook.drawee.view.SimpleDraweeView;
import com.glasses.business.R;
import com.glasses.business.appliction.MyApplication;
import com.glasses.business.base.AppBaseFragment;
import com.glasses.business.entity.CheckMenu;
import com.glasses.business.event.BussEvent;
import com.glasses.business.http.NetUtils;
import com.glasses.business.utils.AliUpLoadCallBack;
import com.glasses.business.utils.AliyunUploadUtils;
import com.glasses.business.utils.TimeUtils;
import com.glasses.business.utils.Tools;
import com.google.gson.Gson;
import com.pizidea.imagepicker.AndroidImagePicker;
import com.pizidea.imagepicker.bean.ImageItem;
import com.pizidea.imagepicker.image.ImagesGridActivity;

import net.neiquan.applibrary.wight.AlertChooser;
import net.neiquan.okhttp.NetCallBack;
import net.neiquan.okhttp.ResultModel;

import org.haitao.common.utils.AppLog;
import org.haitao.common.utils.BitmapUtis;
import org.haitao.common.utils.CameraUtils;
import org.haitao.common.utils.ToastUtil;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

import butterknife.ButterKnife;
import butterknife.InjectView;
import butterknife.OnClick;
import de.greenrobot.event.EventBus;

/**
 * Author：邓勇军
 * English Name：Deng,The Sky Fucker!
 * Email：dandycoder@126.com
 * Date：2017/3/8
 * Version：1.0
 */

public class AddLightOrderFragment extends AppBaseFragment {
    @InjectView(R.id.upLightOrder)
    LinearLayout upLightOrder;
    @InjectView(R.id.writeLightOrder)
    TextView writeLightOrder;
    @InjectView(R.id.upLightImg)
    SimpleDraweeView upLightImg;
    @InjectView(R.id.upLightTime)
    TextView upLightTime;
    @InjectView(R.id.leftEyeSph)
    TextView leftEyeSph;
    @InjectView(R.id.leftEyeCyl)
    TextView leftEyeCyl;
    @InjectView(R.id.leftEyeAxl)
    TextView leftEyeAxl;
    @InjectView(R.id.rightEyeSph)
    TextView rightEyeSph;
    @InjectView(R.id.rightEyeCyl)
    TextView rightEyeCyl;
    @InjectView(R.id.rightEyeAxl)
    TextView rightEyeAxl;
    @InjectView(R.id.eyesPd)
    TextView eyesPd;
    @InjectView(R.id.upLightLL)
    LinearLayout upLightLL;
    private String content;
    private int type = -1;
    private String srcPath;

    @Override
    public int getRootViewId() {
        if (!EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().register(this);
        }
        return R.layout.fragment_light_add;
    }

    public void onEventMainThread(BussEvent event) {
        if (event.getState() == BussEvent.Save_Light_Order) {
            CheckMenu checkMenu = (CheckMenu) event.getMessage();
            setGlassOrderViews(checkMenu);
            content = new Gson().toJson(checkMenu);
            setViewVisible(View.GONE, View.GONE, View.GONE, View.VISIBLE);
            type = 0;
        }
    }

    private void setGlassOrderViews(CheckMenu checkMenu) {
        eyesPd.setText(checkMenu.getEyesPD());
        String leftAXL = checkMenu.getLeftAXL();
        if (!TextUtils.isEmpty(leftAXL)) {
            leftEyeAxl.setText(leftAXL);
        }
        leftEyeCyl.setText(checkMenu.getLeftCYL());
        leftEyeSph.setText(checkMenu.getLeftSPH());
        String rightAXL = checkMenu.getRightAXL();
        if (!TextUtils.isEmpty(rightAXL)) {
            rightEyeAxl.setText(rightAXL);
        }
        rightEyeCyl.setText(checkMenu.getRightCYL());
        rightEyeSph.setText(checkMenu.getRightSPH());
        upLightTime.setText("更新时间:" + TimeUtils.getTime(checkMenu.getUpdateTime()));
    }

    private void upCheckMenu(String content, int type) {
        Tools.showDialog(getActivity());
        NetUtils.getInstance().checkMenu(content, type, new NetCallBack() {
            @Override
            public void onSuccess(String response, String mssage, ResultModel model) {
                Tools.dismissWaitDialog();
                ToastUtil.shortShowToast(mssage);
                EventBus.getDefault().post(new BussEvent(BussEvent.Save_Light_Order));
                MyApplication.getInstance().manager.onBackPressed();
            }

            @Override
            public void onFail(boolean dataError, int errorCode, String mssage) {
                Tools.dismissWaitDialog();
                ToastUtil.shortShowToast(mssage);
            }
        }, null);
    }


    @Override
    public void setViews() {
        setTitleTv("添加验光单");
        setNextTv_("保存");
        setNextOnClick(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                upCheckMenu(content, type);
            }
        });
    }

    @Override
    public void initData() {

    }

    @Override
    public boolean mainTabShow() {
        return false;
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        // TODO: inflate a fragment view
        View rootView = super.onCreateView(inflater, container, savedInstanceState);
        ButterKnife.inject(this, rootView);
        return rootView;
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        ButterKnife.reset(this);
        EventBus.getDefault().unregister(this);
    }

    @OnClick({R.id.upLightOrder, R.id.writeLightOrder})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.upLightOrder:
                showAlertChooser();
                break;
            case R.id.writeLightOrder:
                open(new HandLightFragment());
                break;
        }
    }

    private static final int MY_PERMISSIONS_REQUEST_CALL_PHONE = 6;
    private static final int MY_PERMISSIONS_REQUEST_CALL_PHONE2 = 7;

    private void showAlertChooser() {
        new AlertChooser.Builder(getActivity()).setTitle("选择图片").addItem("相机", new AlertChooser.OnItemClickListener() {
            @Override
            public void OnItemClick(AlertChooser chooser) {
//                Camerautils_.takePhoto(getActivity());
                chooser.dismiss();
//                AppLog.e("=================相机==================" + Camerautils_.photoPath);
//                startActivityForResult(new Intent("android.media.action.IMAGE_CAPTURE"), TAKE_PICTURE);
                if (ContextCompat.checkSelfPermission(getActivity(),
                        Manifest.permission.CAMERA)
                        != PackageManager.PERMISSION_GRANTED) {
                    ActivityCompat.requestPermissions(getActivity(),
                            new String[]{Manifest.permission.CAMERA},
                            MY_PERMISSIONS_REQUEST_CALL_PHONE2);
                } else {
                    Intent it = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                    startActivityForResult(it, 1);
                }
            }
        }).addItem("相册", new AlertChooser.OnItemClickListener() {
            @Override
            public void OnItemClick(AlertChooser chooser) {
                chooser.dismiss();
                if (ContextCompat.checkSelfPermission(getActivity(),
                        Manifest.permission.WRITE_EXTERNAL_STORAGE)
                        != PackageManager.PERMISSION_GRANTED) {
                    ActivityCompat.requestPermissions(getActivity(),
                            new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE},
                            MY_PERMISSIONS_REQUEST_CALL_PHONE2);
                } else {
                    AndroidImagePicker.getInstance().setSelectMode(AndroidImagePicker.Select_Mode.MODE_SINGLE);
                    //AndroidImagePicker.Select_Mode.MODE_SINGLE单选模式
                    //AndroidImagePicker.Select_Mode.MODE_MULTI多选模式
                    //AndroidImagePicker.getInstance().setSelectLimit(MAX_NUM);//多选模式下  最多选多少张
                    AndroidImagePicker.getInstance().setShouldShowCamera(false);//相册里面是否显示拍照按钮
                    Intent intent = new Intent(getActivity(), ImagesGridActivity.class);
                    startActivityForResult(intent, CameraUtils.LOCAL_PICTURE);
                }
            }
        }).setNegativeItem("取消", new AlertChooser.OnItemClickListener() {
            @Override
            public void OnItemClick(AlertChooser chooser) {
                chooser.dismiss();
            }
        }).show();
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults)
    {

        if (requestCode == MY_PERMISSIONS_REQUEST_CALL_PHONE)
        {
            if (grantResults[0] == PackageManager.PERMISSION_GRANTED)
            {
                Intent it = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                startActivityForResult(it, 1);
            } else
            {
                // Permission Denied
                ToastUtil.shortShowToast("拍照权限拒绝!");
            }
        }

        if (requestCode == MY_PERMISSIONS_REQUEST_CALL_PHONE2)
        {
            if (grantResults[0] == PackageManager.PERMISSION_GRANTED)
            {
                AndroidImagePicker.getInstance().setSelectMode(AndroidImagePicker.Select_Mode.MODE_SINGLE);
                //AndroidImagePicker.Select_Mode.MODE_SINGLE单选模式
                //AndroidImagePicker.Select_Mode.MODE_MULTI多选模式
                //AndroidImagePicker.getInstance().setSelectLimit(MAX_NUM);//多选模式下  最多选多少张
                AndroidImagePicker.getInstance().setShouldShowCamera(false);//相册里面是否显示拍照按钮
                Intent intent = new Intent(getActivity(), ImagesGridActivity.class);
                startActivityForResult(intent, CameraUtils.LOCAL_PICTURE);
            } else
            {
                // Permission Denied
                ToastUtil.shortShowToast("获取相册权限拒绝!");
            }
        }
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == CameraUtils.LOCAL_PICTURE) {
            List<ImageItem> imageList = AndroidImagePicker.getInstance().getSelectedImages();
            if (imageList != null && imageList.size() > 0) {
                initAliyun(imageList.get(0).getPath());
//                mImageView.setImageURI("file://" + imageList.get(0).getPath());
            }
        } else if (requestCode == CameraUtils.TAKE_PICTURE) {
//            initAliyun(CameraUtils.photoPath);
//            mImageView.setImageURI("file://" + CameraUtils.photoPath);

            Bundle extras = data.getExtras();
            Bitmap b = (Bitmap) extras.get("data");
            String name = new SimpleDateFormat("yyyyMMddhhmmss").format(new Date());
            String fileNmae = Environment.getExternalStorageDirectory().toString() + File.separator + "dong/image/" + name + ".jpg";
            srcPath = fileNmae;
            System.out.println(srcPath + "----------保存路径1");
            File myCaptureFile = new File(fileNmae);
            try {
                if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
                    if (!myCaptureFile.getParentFile().exists()) {
                        myCaptureFile.getParentFile().mkdirs();
                    }
                    BufferedOutputStream bos;
                    bos = new BufferedOutputStream(new FileOutputStream(myCaptureFile));
                    b.compress(Bitmap.CompressFormat.JPEG, 80, bos);
                    bos.flush();
                    bos.close();
                    initAliyun(srcPath);
                } else {
                    ToastUtil.shortShowToast("保存失败，SD卡无效");
                }
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        super.onActivityResult(requestCode, resultCode, data);
    }

    private void setViewVisible(int glassImgVisible, int glassOrderVisible, int glassHandleVisible, int glassUpVisible) {
        upLightImg.setVisibility(glassImgVisible);
        upLightOrder.setVisibility(glassOrderVisible);
        writeLightOrder.setVisibility(glassHandleVisible);
        upLightLL.setVisibility(glassUpVisible);
    }

    private void initAliyun(final String path) {
        Tools.showWaitDialog(getContext(), "请稍后...");
        BitmapUtis.compress(path, 600, 800, new BitmapUtis.CompressCallback() {

            @Override
            public void onsucces(String s) {
                AliyunUploadUtils.getInstance(getActivity()).uploadPhoto(s, new AliUpLoadCallBack() {

                    @Override
                    public void onSuccess(String RootPath, String bucket, String fileName) {
                        Tools.dismissWaitDialog();
                        ToastUtil.shortShowToast("上传图片成功！");
                        content = RootPath + fileName;
                        setViewVisible(View.VISIBLE, View.GONE, View.GONE, View.GONE);
                        upLightImg.setImageURI(content);
                        type = 1;
                    }

                    @Override
                    public void onFailure(String objectKey, OSSException ossException) {
                        Tools.dismissWaitDialog();
                        ToastUtil.shortShowToast("上传图片到服务器失败...请重新尝试");
                    }
                });
            }

            @Override
            public void onfail() {
                Tools.dismissWaitDialog();
                ToastUtil.shortShowToast("图片太大或者已损坏，请重新选择图片");
            }
        });
    }
}
